<template>
  <div class="cart-page">
    <div class="cart-header">
      <el-button 
        icon="ArrowLeft"
        @click="$router.push('/')"
        style="margin-right: 16px"
      >返回主页</el-button>
      <h2>我的购物车</h2>
    </div>
    
    <div class="cart-content" v-loading="loading">
      <!-- 购物车为空时显示 -->
      <div v-if="!cartItems.length" class="empty-cart">
        <el-empty description="购物车还是空的" >
          <el-button type="primary" @click="$router.push('/')">去逛逛</el-button>
        </el-empty>
      </div>

      <!-- 购物车有商品时显示 -->
      <div v-else class="cart-items">
        <el-table :data="cartItems" style="width: 100%">
          <el-table-column label="商品信息" min-width="400">
            <template #default="scope">
              <div class="product-info">
                <img :src="scope.row.productImage" class="product-image" />
                <div class="product-details">
                  <div class="product-name">{{ scope.row.productName }}</div>
                  <div class="product-farm">{{ scope.row.farmName }}</div>
                  <div class="product-id">商品ID: {{ scope.row.productId }}</div>
                  <div class="seller-id">卖家ID: {{ scope.row.userId }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="单价" width="120">
            <template #default="scope">
              <div class="price">¥{{ scope.row.price }}</div>
            </template>
          </el-table-column>
          
          <el-table-column label="数量" width="120">
            <template #default="scope">
              <div class="quantity">
                {{ scope.row.quantity }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="库存" width="120">
            <template #default="scope">
              <div class="stock">
                {{ scope.row.stock }}
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="小计" width="120">
            <template #default="scope">
              <div class="subtotal">¥{{ calculateSubtotal(scope.row) }}</div>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button 
                type="danger" 
                size="small" 
                @click="removeItem(scope.row.productId)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 购物车底部 -->
        <div class="cart-footer">
          <div class="cart-summary">
            <div class="summary-item">
              <span>商品总数：</span>
              <span class="total-quantity">{{ totalItems }}件</span>
            </div>
            <div class="summary-item">
              <span>总计金额：</span>
              <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
          </div>
          <div class="cart-actions">
            <el-button type="primary" size="large" @click="checkout" :disabled="!cartItems.length">
              结算
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const cartItems = ref([])

// 计算小计
const calculateSubtotal = (item) => {
  return (item.price * item.quantity).toFixed(2)
}

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
})

// 计算总件数
const totalItems = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.quantity
  }, 0)
})

// 加载购物车数据
const loadCartItems = async () => {
  try {
    loading.value = true
    const response = await request({
      url: '/api/orders/cart',
      method: 'get'
    })
    
    console.log('购物车接口返回数据:', response)
    
    if (response && Array.isArray(response)) {
      cartItems.value = response
      console.log('处理后的购物车数据:', cartItems.value)
    } else {
      cartItems.value = []
      ElMessage.warning('购物车数据格式不正确')
    }
  } catch (error) {
    console.error('获取购物车数据失败:', error)
    ElMessage.error('获取购物车数据失败')
    cartItems.value = []
  } finally {
    loading.value = false
  }
}

// 删除商品
const removeItem = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    const response = await request({
      url: `/api/orders/cart/${productId}`,
      method: 'delete'
    })
    
    if (response?.code === 200) {
      await loadCartItems() // 重新加载购物车数据
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 结算
const checkout = async () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车是空的')
    return
  }
  
  try {
    loading.value = true
    const response = await request({
      url: '/api/orders/cart/checkout',
      method: 'post'
    })
    
    console.log('结算响应:', response)
    
    // 后端返回的是总金额数字，如果能获取到就表示成功
    if (response !== null && response !== undefined) {
      const totalAmount = Number(response)
      ElMessage.success(`结算成功，总金额：¥${totalAmount.toFixed(2)}`)
      await loadCartItems() // 重新加载购物车数据
    } else {
      ElMessage.error('结算失败，请稍后重试')
    }
  } catch (error) {
    console.error('结算失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('结算失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadCartItems()
})
</script>

<style scoped>
.cart-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.cart-header {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.cart-header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 5px;
}

.product-farm {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.product-id, .seller-id {
  font-size: 12px;
  color: #999;
  margin-bottom: 2px;
}

.price, .subtotal {
  color: #ff6b00;
  font-weight: bold;
}

.quantity {
  min-width: 40px;
  text-align: center;
}

.stock {
  min-width: 40px;
  text-align: center;
}

.cart-footer {
  margin-top: 20px;
  padding: 20px;
  background: #f8f8f8;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-summary {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.summary-item {
  font-size: 16px;
}

.total-quantity {
  color: #333;
  font-weight: bold;
}

.total-price {
  color: #ff6b00;
  font-size: 24px;
  font-weight: bold;
}

.cart-actions {
  display: flex;
  gap: 10px;
}
</style> 